package com.seventhdawn.gwt.rcx.server;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * Convenience base class for custom RPC {@link javax.servlet.Filter filters}.
 * <p>
 * Concrete filters should call {@link #doFilterInit(String) doFilterInit}
 * within their
 * {@link #doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 * doFilter} method.
 * 
 * @author vojtech.szocs
 */
public abstract class AbstractRPCFilter extends RPCSerializationPolicyProvider implements Filter {

    private FilterConfig filterConfig;
    private String requestContextPath;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        filterConfig = null;
    }

    @Override
    protected ServletContext getServletContext() {
        return filterConfig.getServletContext();
    }

    @Override
    protected String getRequestContextPath() {
        return requestContextPath;
    }

    private void setRequestContextPath(String requestContextPath) {
        this.requestContextPath = requestContextPath;
    }

    /**
     * Basic filter runtime initialization.
     * <p>
     * Concrete filters should call this method within
     * {@link #doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     * doFilter}.
     */
    protected void doFilterInit(String requestContextPath) throws ServletException {
        if (filterConfig == null)
            throw new ServletException("doFilter() called before init()");

        setRequestContextPath(requestContextPath);
    }

    /**
     * @return Filter configuration object.
     */
    protected FilterConfig getFilterConfig() {
        return filterConfig;
    }

    /**
     * Returns a boolean parameter value obtained from the filter configuration.
     */
    protected boolean getBooleanInitParam(String paramName, boolean defaultValue) {
        String paramValue = filterConfig.getInitParameter(paramName);

        if (paramValue != null)
            return Boolean.valueOf(paramValue);
        else
            return defaultValue;
    }

}
